#define  _CRT_SECURE_NO_WARNINGS
class Solution {
    vector<vector<bool>> jug;
    int m, n;
    int dx[4] = { 0,0,1,-1 };
    int dy[4] = { 1,-1,0,0 };
    bool dfs(vector<vector<char>>& board, string& word, string path, int r, int c)
    {
        if (word == path) return true;

        for (int i = 0; i < 4; i++)
        {
            int x = r + dx[i];
            int y = c + dy[i];
            if (x >= 0 && y >= 0 && x < m && y < n && jug[x][y] && board[x][y] == word[path.size()])
            {
                jug[x][y] = false;
                if (dfs(board, word, path + board[x][y], x, y)) return true;
                jug[x][y] = true;
            }
        }
        return false;
    }

public:
    bool exist(vector<vector<char>>& board, string word) {
        string tmp;
        m = board.size(), n = board[0].size();
        jug.resize(m, vector<bool>(n, true));
        for (int i = 0; i < m; i++)
            for (int j = 0; j < n; j++)
                if (board[i][j] == word[0])
                {
                    jug[i][j] = false;
                    if (dfs(board, word, tmp + board[i][j], i, j)) return true;
                    jug[i][j] = true;
                }
        return false;
    }
};